<template>
  <div class="editor-wrapper">
    <div :id="editorId"></div>
  </div>

</template>

<script>
import Editor from 'wangeditor'
import axios, { baseUrl } from '@/libs/api.request'

import 'wangeditor/release/wangEditor.min.css'
import { oneOf } from '@/libs/tools'
import iView from 'view-design'
import CryptoJS from 'crypto-js'

export default {
  name: 'Editor',
  data () {
    return {
      uploadUrl: baseUrl + 'Attachment/editor',
      files: {}
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    /**
     * 绑定的值的类型, enum: ['html', 'text']
     */
    valueType: {
      type: String,
      default: 'html',
      validator: (val) => {
        return oneOf(val, ['html', 'text'])
      }
    },
    /**
     * @description 设置change事件触发时间间隔
     */
    changeInterval: {
      type: Number,
      default: 200
    },
    /**
     * @description 是否开启本地存储
     */
    cache: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    editorId () {
      return `editor${this._uid}`
    }
  },
  methods: {
    setHtml (val) {
      this.editor.txt.html(val)
    },
    doUpload (insert) {
      let vm = this
      let files = vm.files
      if (Object.keys(vm.files).length === 0) {
        return false
      }
      let formData = new window.FormData()
      for (var i in files) {
        formData.append(i, files[i])
      }
      let options = { // 设置axios的参数
        url: vm.uploadUrl,
        data: formData,
        method: 'post',
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      // 执行上传
      const msg = iView.Message.loading({
        content: '上传中...',
        duration: 0
      })
      axios.request(options).then((res) => {
        iView.Message.success({
          content: res.data.msg
        })
        let fileList = res.data.data
        for (var i in fileList) {
          insert(fileList[i].previewUrl)
        }
        setTimeout(msg)
      })
    }
  },
  mounted () {
    let vm = this
    this.editor = new Editor(`#${this.editorId}`)
    // 配置开始
    this.editor.customConfig = {
      onchangeTimeout: this.changeInterval,
      customAlert: function (res) {
        iView.Notice.warning({
          title: res,
          desc: false
        })
      },
      onchange: (html) => {
        let text = this.editor.txt.text()
        if (this.cache) localStorage.editorCache = html
        this.$emit('input', this.valueType === 'html' ? html : text)
        this.$emit('on-change', html, text)
      },
      customUploadImg: function (files, insert) {
        // 先检查hash
        let hashList = []
        let n = 0
        for (var i in files) {
          var reader = new FileReader()
          reader.readAsArrayBuffer(files[i])
          reader.onload = function (evt) {
            n++
            var fileString = evt.target.result
            var wordArray = CryptoJS.lib.WordArray.create(fileString)
            var hash = CryptoJS.SHA256(wordArray).toString()
            vm.files[hash] = files[i]
            hashList.push(hash)
            if (n >= files.length) {
              // 等待读取完毕所有文件的哈希
              axios.request({ url: vm.uploadUrl, data: { hash: hashList.join(',') }, method: 'post' }).then((res) => {
                if (res.data.code) {
                  let fileList = res.data.data
                  if (fileList.length === files.length) {
                    iView.Message.success({ content: '极速闪传成功' })
                  }
                  for (var i in fileList) {
                    insert(fileList[i].previewUrl) // 插入到编辑器展示
                    // 删掉同样的hash文件
                    delete vm.files[fileList[i].sha256]
                  }
                }
                vm.doUpload(insert)
              })
            }
          }
        }
      }
    }
    // create这个方法一定要在所有配置项之后调用
    this.editor.create()
    // 如果本地有存储加载本地存储内容
    let html = this.value || localStorage.editorCache
    if (html) this.editor.txt.html(html)
  }
}
</script>

<style lang="less">
.editor-wrapper *{
  z-index: 100 !important;
}
.w-e-menu{
  z-index: 2 !important;
}
.w-e-text-container{
  z-index: 1 !important;
}

.toolbar {
    border: 1px solid #ccc;
}
.text {
    border: 1px solid #ccc;
    height: 600px;
}

</style>
